
//
// 120316 - AH - (Bergen Off. Bibliotek *) Created.
// 120713a- AH - Removed documented away code.
// 120713b- AH - Took FILE_ID in use.
//

package org.soekrat.server.servlets.file;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.japril.servlet.HttpRequestDef;
import org.soekrat.server.io.db.DbFile;
import org.soekrat.server.io.db.SoekratDAO;
import org.soekrat.server.io.db.SoekratDAOFactory;
import org.soekrat.server.servlets.AbstractSoekratHttpServlet;
import org.soekrat.server.servlets.SoekratResponse;

/**
 * <p>
 *   Implements request to look up binary data.
 * </p>
 * @author Arne Halvorsen (AH) 
 * @author Laetitia Le Chatton (LLC)
 */
@SuppressWarnings("serial")
public final class LookupFileHttpServlet extends AbstractSoekratHttpServlet 
{
  /**
   * <p>
   *   Constructor.
   * </p>
   */
  public LookupFileHttpServlet(){}
 
  @Override
  protected void handleRequest(HttpServletRequest req, HttpServletResponse res)
    throws ServletException, IOException 
  {
    HttpRequestDef def=getHttpRequestDef();
    
    if (!hasParameters(req))
    {
      PrintWriter pw=printSimpleHtmlStart(res, "Lookup File");
      pw.println(def.compileApiHtml());
      printSimpleHtmlEnd(pw);
      return;
    }
    else
    {
      if (!validate(res, def, req)) return;
      
      SoekratResponse r=new SoekratResponse();  
    
      long key=def.fetch(FILE_ID.name(), req).getLongValue();  
    
      SoekratDAO dao=new SoekratDAOFactory().create();
      
      DbFile file=dao.getFile(key);
          
      if (file==null)
      {
        r.status("File not found");
      }
      else
      {
        r.response(file);
      }
     
      respond(res, r);
    }
  }
  
  @Override
  public HttpRequestDef getHttpRequestDef() 
  {
    return new HttpRequestDef("/soekrat_server/lookup_file")
      .desc("Lookup File").parameter(FILE_ID);
  }
  
}
